// pages/coreAdmin/gateDeclaration/gateDeclaration.js
const app = getApp()
import config from '../../../utils/config.js';
import util from '../../../utils/util.js';
import Toast from '../../../vant/toast/toast';
import Dialog from '../../../vant/dialog/dialog';
import {
  comModel
} from '../../../models/com';
const com = new comModel();

import {
  indexModel
} from '../../../models/index';
const index = new indexModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    config:config,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '档口报单',
      //  导航栏 中间的标题
    },
    height: app.globalData.height,
    navHeight: app.globalData.barheight,
    realWindowHeight: app.globalData.realWindowHeight,
    scroll_height:'',

    id:'', // 供应商ID
    type:'',// 父级页面 1 商品供应商 2 清单供应商

    mulist:[
      {id:"全部",categoryName:"全部"}
    ],
    selectMu:'全部',  //当前选择一级菜单标识
    selectMu2:'', //当前选择二级菜单标识

    show:false,
    goodList:[],  // 商品规格列表
    good:{}, // 选择规格
    goodIndex: '', // 选择第几个

    timer:'',
    name:'',

    allPage: 0, // 所有页数
    page: 1, // 第几页
    endFlag: false, // 是否到最后
    dataList: [], // 商品列表
    searchWord:'',

    fLoad:false,   // 是否刷新数据
    showInputDailog: false, // 计步器点击input输入弹窗
    currentValue: '', // 计步器点击input输入弹窗中input中的数值
    isfocus: false, // 计步器点击input输入弹窗中input设置自动聚焦
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 设置content高度
    var scroll_height = this.data.realWindowHeight-this.data.navHeight-this.data.height-(103 / 750 * wx.getSystemInfoSync().windowWidth)

    var id = options.id;
    this.setData({
      scroll_height: scroll_height,
      id:id,
      selectMu: options.tid || '全部'
    })
    this.getcategoryList();
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.fLoad){
      this.reData();
      this.getList();
    }
  },

  // 点击一级菜单
  onTopMu(e){
    var id = e.currentTarget.dataset.id;
    this.setData({
      selectMu2:''
    })
    if(this.data.selectMu==id){
        this.reData();
        this.getList();
        return
    }else{
      this.setData({
        selectMu:id
      })
    }
    this.reData();
    this.getList();
   
  },

  // 点击二级菜单
  onTopTwe(e){
    var id = e.currentTarget.dataset.id;
    this.setData({
      selectMu2:id
    })
    this.reData();
    this.getList();
  },

  // 获取所有分类
  getcategoryList(){
    com.apiCategoryList({}, res => {
      var shield = {
        id:'屏蔽商品',
        categoryName:'屏蔽商品'
      }
      res.push(shield);
      this.setData({
        mulist:this.data.mulist.concat(res)
      })
    })
  },

  // 搜一搜
  searchInput(event){
    clearTimeout(this.data.timer)
    var that = this;
    this.setData({
      timer: setTimeout(function(){
        that.setData({
          page:1,
          dataList:[],
          endFlag: false,
          searchWord:event.detail.value
        })
        that.getList();
      },1*1000)
    })
  },

  // 查询档口报单列表
  getList(){
    com.apiStallShopCar({
      page: this.data.page,
      searchWord:this.data.searchWord,
      categoryId:this.data.selectMu=="屏蔽商品"?'':(this.data.selectMu2?this.data.selectMu2:(this.data.selectMu=="全部"?'':this.data.selectMu)),
      shieldStatus:this.data.selectMu=="屏蔽商品"?1:0, //是否屏蔽当前员工 0否1是
      limit: 10,
    }, res =>{
      if (res.list.length > 0) {
        var page = this.data.page;
        var endFlag = false;
        var allPage = res.allPage;
        if (page == allPage) {
          endFlag = true;
        } else {
          page += 1;
        }
        var dataList = this.data.dataList;
        if (page != 1) {
          dataList = dataList.concat(res.list);
        } else {
          dataList = res.list;
        }
        this.setData({
          dataList: dataList,
          endFlag: endFlag,
          page: page
        });
      }
    })
  },

  // 商品滑动至底部
  producScroll(){
    if (this.data.endFlag) {
      util.msg('没有更多了~');
      return;
    } else {
      this.getList();
    }
  },

  // 初始化商品列表
  reData(){
    this.setData({
      allPage: 0, // 所有页数
      page: 1, // 第几页
      endFlag: false, // 是否到最后
      dataList: [], // 商品列表
    })
  },

  // 点击加号减号计数
  onChange: util.throttle(function (event)  {
    var goodsCount = event.detail
    goodsCount = goodsCount?goodsCount:0

    var goodsId = event.currentTarget.dataset.id;
    var index = event.currentTarget.dataset.index;
    var sindex = event.currentTarget.dataset.sindex;
    var dataList = this.data.dataList;

	  var that = this;
    let oldCount = dataList[index].goodList[sindex].goodCount + '' // 当前商品原数量
    dataList[index].goodList[sindex].goodCount = goodsCount //点击后当前店铺下当前商品的数量
    if(oldCount === goodsCount){ // 值没有变化
      return
    }

    this.setData({
      dataList: dataList
    })
    if(this.data.show){ // 多规格
      var goodList = this.data.goodList;
      goodList[sindex].goodCount = goodsCount
      that.setData({
        goodList: goodList
      })
    }

    // 验证计量可否为小数 1 是 0否
    var decimalStatus = dataList[index].goodList[sindex].decimalStatus 
    if(decimalStatus!=1){
      if(!util.valZe(goodsCount)){
        util.msg('当前商品数量只能为整数');
        dataList[index].goodList[sindex].goodCount = parseInt(oldCount);
        this.setData({
          dataList: dataList
        })
        if(this.data.show){ // 多规格
          var goodList = this.data.goodList;
          goodList[sindex].goodCount = parseInt(oldCount)
          this.setData({
            goodList: goodList
          })
        }
        return;
      }
    }else{
      if(!util.isMoney(goodsCount)){
        util.msg('商品数量格式有误');
        dataList[index].goodList[sindex].goodCount = oldCount;
        this.setData({
          dataList: dataList
        })
        if(this.data.show){ // 多规格
          var goodList = this.data.goodList;
          goodList[sindex].goodCount = oldCount
          this.setData({
            goodList: goodList
          })
        }
        return;
      }
    }

    com.apiAddshopNoLoad({
      goodsId:goodsId,
      goodsCount:goodsCount?goodsCount:0
    }, res => {
      if (res.code == 200) {
      } else {
        util.msg(res.msg)
        dataList[index].goodList[sindex].goodCount = parseInt(oldCount);
        that.setData({
          dataList: dataList
        })
        if(that.data.show){ // 多规格
          var goodList = that.data.goodList;
          goodList[sindex].goodCount = parseInt(oldCount)
          that.setData({
            goodList: goodList
          })
        }
      }
    })
  },500),

  // 点击input弹窗
  onInput(event)  {
    var goodsId = event.currentTarget.dataset.id;
    var index = event.currentTarget.dataset.index;
    var sindex = event.currentTarget.dataset.sindex;
    this.submitData = {
      goodsId: goodsId,
      index: index,
      sindex: sindex
    }
    this.setData({
      currentValue: event.currentTarget.dataset.currentval,
      showInputDailog: true
    });
    // van-popup中有一个动画效果，所以input的focus效果要做一个延时
    var that = this
    setTimeout(()=>{
      that.setData({
        isfocus: true
      })
    },35)
  },
  onFocus(event) {
    if (event.detail.value === '0') {
      this.setData({ currentValue: '' })
    }
  },
  onBlur(event) {
    if (event.detail.value === '') {
      this.setData({ currentValue: '0' })
    }
  },
  // 点击input弹窗-取消
  onCancel() {
    this.setData({showInputDailog: false});
  },
  // 点击input弹窗-确认
  onSure(event) {
    var { goodsCount } = event.detail.value
    var goodsId = this.submitData.goodsId;
    var index = this.submitData.index;
    var sindex = this.submitData.sindex;
    var dataList = this.data.dataList;

    if(Number(goodsCount) > 99999) { // 最大范围99999
      util.msg('最大输入99999')
      this.setData({
        currentValue: 99999
      })
      return
    }
	  var that = this;
    let oldCount = dataList[index].goodList[sindex].goodCount + '' // 当前商品原数量
    dataList[index].goodList[sindex].goodCount = goodsCount //点击后当前店铺下当前商品的数量
    if(oldCount === goodsCount){ // 值没有变化,则关闭弹窗
      this.onCancel()
      return
    }

    // 先设置列表中的值，之后要进行与旧值进行比较
    that.setData({
      dataList: dataList
    })
    if(this.data.show){ // 多规格的还要对底部弹出层中的数据进行修改
      var goodList = this.data.goodList;
      goodList[sindex].goodCount = goodsCount
      that.setData({
        goodList: goodList
      })
    }

    // 验证计量可否为小数（decimalStatus 1 是 0否）
    var decimalStatus = dataList[index].goodList[sindex].decimalStatus 
    if(decimalStatus!=1){ // 整数
       // 判断是否为整数
      if(!util.valZe(goodsCount)){ // 不是整数，则把修改的数据改回旧数据
        util.msg('当前商品数量只能为整数');
        dataList[index].goodList[sindex].goodCount = parseInt(oldCount);
        that.setData({
          dataList: dataList
        })
        if(that.data.show){ // 多规格
          var goodList = that.data.goodList;
          goodList[sindex].goodCount = parseInt(oldCount)
          that.setData({
            goodList: goodList
          })
        }
        return;
      }
    }else{ // 小数
       // 判断是否为两位小数的格式
      if(!util.isMoney(goodsCount)){ // 不是小数，则把修改的数据改回旧数据
        util.msg('商品数量格式有误');
        dataList[index].goodList[sindex].goodCount = oldCount;
        that.setData({
          dataList: dataList
        })
        if(this.data.show){ // 多规格
          var goodList = this.data.goodList;
          goodList[sindex].goodCount = oldCount
          that.setData({
            goodList: goodList
          })
        }
        return;
      }
    }

    // 请求接口
    com.apiAddshop({
      goodsId:goodsId,
      goodsCount:goodsCount?goodsCount:0
    }, res => {
      if (res.code == 200) { // 成功
        that.onCancel() // 关闭弹窗
      } else { // 失败，则把修改的数据改回旧数据
        util.msg(res.msg)
        dataList[index].goodList[sindex].goodCount = parseInt(oldCount);
        that.setData({
          dataList: dataList
        })
        if(this.data.show){ // 多规格
          var goodList = this.data.goodList;
          goodList[sindex].goodCount = parseInt(oldCount)
          that.setData({
            goodList: goodList
          })
        }
      }
    })
    
  },

  // 选择规格
  selectMore(e){
    this.setData({
      show:true
    })
    var productId = e.currentTarget.dataset.id;
    var dataList = this.data.dataList;
    for(var i=0;i<dataList.length;i++){
      if(dataList[i].productId == productId){
        this.setData({
          goodList:dataList[i].goodList,
          good:dataList[i].goodList[0],
          goodIndex: i
        })
        break
      }
    }
  },
  onClose(){
    this.setData({
      show:false
    })
  },

  // 商品长按事件
  //touch start
  handleTouchStart: function(e) {   
    this.startTime = e.timeStamp;   
  }, 
  //touch end
  handleTouchEnd: function(e) {   
    this.endTime = e.timeStamp;   
  }, 
  handleClick: function(e) {   
    if (this.endTime - this.startTime < 350) {     
    console.log("点击");   
    } 
  }, 
  handleLongPress: function(e) {   
    var productId = e.currentTarget.dataset.id
    var that = this;
    if(this.data.selectMu=='屏蔽商品'){
        return
    }
    Dialog.confirm({
      message: '确认屏蔽该商品？',
    }).then(() => {
      that.onShield(productId)
    }).catch(() => {

    });
  },
  
  // 屏蔽商品
  onShield(productId){
    com.apiShield({productId:productId}, res => {
      util.msg('已屏蔽');
      this.reData();
      this.getList();
    })
  },

  // 取消屏蔽
  cancelShield(e){
    var productId = e.currentTarget.dataset.id
    com.apicancelShield({productId:productId}, res => {
      this.reData();
      this.getList();
    })
  },

  // 商品详情
  onDetail: util.throttle(function (e) {
    var productId = e.currentTarget.dataset.id
    if (productId) 
      wx.navigateTo({
        url: '/pages/commodity/commodityInfo/commodityInfo?productId=' + productId,
      })
  }),

  // 报单统计
  onStatistics: util.throttle(function (e) {
    wx.switchTab({
      url: '/pages/statistics/statistics',
    })
  }),

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 返回不需刷新
    this.setData({
      fLoad:false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      allPage: 0, // 所有页数
      page: 1, // 第几页
      endFlag: false, // 是否到最后
      dataList: [], // 商品列表
      mulist:[
        {id:"全部",categoryName:"全部"}
      ],
    })
    this.getcategoryList();
    this.getList();
    //模拟加载 		
    setTimeout(function () {		
      wx.hideNavigationBarLoading() //完成停止加载 			
      wx.stopPullDownRefresh() //停止下拉刷新 		
    }, 1500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.endFlag) {
      util.msg('没有更多了~');
      return;
    } else {
      this.getList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})